﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;


namespace ProjectBase.Utils
{
	/// <summary>
	/// Summary description for CUtilities.
	/// </summary>
	public class CUtilities
	{
//		public CUtilities()
//		{
//			//
//			// TODO: Add constructor logic here
//			//
//		}
		public static string StringForNull(object x) 
		{
			if ((Convert.IsDBNull(x) 
				|| (x == null))) 
			{
				return "";
			}
			else 
			{
				return x.ToString();
			}
		}

        //public static string StringForUpdateAllowingNULL(string x) 
        //{
        //    if ((StringForNull(x).Trim() == "")) 
        //    {
        //        return "NULL";
        //    }
        //    else 
        //    {
        //        return "N'" + x + "'";
        //    }
        //}

        public static string StringForUpdateAllowingNULL(string x)
        {
            if ((StringForNull(x).Trim() == ""))
            {
                return "NULL";
            }
            else
            {
                return "N'" + x.Replace("'", "´") + "'";
            }
        }

		public static string StringForUpdate(object x)
		{
   			string Str_tmp = null;
   			if (Convert.IsDBNull(x)) 
			{
       			//return "NULL";
       			return "";
   			}
   			else if ((x == null)) 
			{
       			//return "NULL";
       			return "";
   			}
   			else if (x.ToString().Length == 0) 
			{
       			//return "NULL";
       			return "";
   			}
   			else 
			{
       			Str_tmp = x.ToString();
       			Str_tmp = Str_tmp.Replace("'", "´");
       			return Str_tmp;
       			//return "'" + Str_tmp + "'";
   			}
		}

		public static bool IsNumeric(object Expression)
		{
			bool isNum;
			double retNum;
			isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
			return isNum;
		}

        public static bool IsDate(object sdate)
        {
            DateTime dt;
            bool isDate = true;
            try
            {
                dt = DateTime.Parse(sdate.ToString());
            }
            catch
            {
                isDate = false;
            }
            return isDate;
        }

		public static Int32 IntegerForNull(object x)
		{
            try
            {
                if ((x == null))
                {
                    return 0;
                }
                else if (Convert.IsDBNull(x))
                {
                    return 0;
                }
                else if (!IsNumeric(x))
                {
                    return 0;
                }
                else
                {
                    return Convert.ToInt32(x.ToString());
                }
            }catch(Exception ex){
                return 0;   
            }
		}

        public static Int16 SmallIntForNull(object x)
        {
            try
            {
                if ((x == null))
                {
                    return 0;
                }
                else if (Convert.IsDBNull(x))
                {
                    return 0;
                }
                else if (!IsNumeric(x))
                {
                    return 0;
                }
                else
                {
                    return Convert.ToInt16(x.ToString());
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        public static Int64 BigIntegerForNull(object x)
        {
            try
            {
                if ((x == null))
                {
                    return 0;
                }
                else if (Convert.IsDBNull(x))
                {
                    return 0;
                }
                else if (!IsNumeric(x))
                {
                    return 0;
                }
                else
                {
                    return Convert.ToInt64(x.ToString());
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

		public static double DoubleForNull(object x) 
		{
            try
            {
                if ((x == null))
                {
                    return 0;
                }
                else if (Convert.IsDBNull(x))
                {
                    return 0;
                }
                else if (!IsNumeric(x))
                {
                    return 0;
                }
                else
                {
                    return Convert.ToDouble(x.ToString());// (double)x;
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
		}

		public static object NumberForNullAllowingNULL(object x) 
		{
			if ((x == null)) 
			{
				return "NULL";
			}
			else if (Convert.IsDBNull(x)) 
			{
				return "NULL";
			}
			else if ((x.ToString().Length == 0)) 
			{
				return "NULL";
			}
			else if (IsNumeric(x)) 
			{
				if ((int)x == 0) 
				{
					return "NULL";
				}
				else 
				{
					return x;
				}
			}
			else 
			{
				return "NULL";
			}
		}

		public static string ConvertBooleanToYN(bool b) 
		{
			if (b) 
			{
				return "Y";
			}
			else 
			{
				return "N";
			}
		}

        public static int ConvertBooleanToBit(bool b)
        {
            if (b)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    
		public static bool ConvertYNToBoolean(object x) 
		{
			if (Convert.IsDBNull(x)) 
			{
				return false;
			}
			else if ((x.ToString().Trim().ToUpper() == "Y")) 
			{
				return true;
			}
			else 
			{
				return false;
			}
		}

        public static bool ConvertBitToBoolean(int x)
        {
            if (Convert.IsDBNull(x))
            {
                return false;
            }
            else if (x == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool ConvertBitToBoolean(object x)
        {
            if (Convert.IsDBNull(x))
            {
                return false;
            }
            else
            {
                return Boolean.Parse(x.ToString());
            }            
        }

		public static string DateForDisplay(object sDate)
		{
			if (Convert.IsDBNull(sDate) | (sDate == null)) 
			{
				return "";
			}
			else 
			{
                return string.Format("{0:dd/MM/yyyy}", sDate);
			}
		}

		public static string DateTimeForDisplay(object sDate)
		{
			if (Convert.IsDBNull(sDate) | (sDate == null)) 
			{
				return "";
			}
			else 
			{
				return string.Format(sDate.ToString(), "dd/MM/yyyy hh:mm:ss tt");
			}
		}

		public static string DateForUpdate(object sDate)
		{
			if (Convert.IsDBNull(sDate) | (sDate == null)) 
			{
				return "";
			}
			else 
			{
				return string.Format(sDate.ToString(), "MM/dd/yyyy");
			}
		}

        public static string ConvertDate2YMD(object date)
        {
            if (Convert.IsDBNull(date))
            {
                return "";
            }
            else if ((date == null))
            {
                return "";
            }
            else if (StringForNull(date).Equals(""))
            {
                return "";
            }
            else if (date.ToString().Length < 3)
            {
                return "";
            }
            else
            {
                string[] arrDate = date.ToString().Split(new Char[] { '/' });
                return arrDate[2] + "/" + arrDate[1] + "/" + arrDate[0];
            }
        }

        public static string ConvertDate2YMDAlowNull(object date)
        {
            if (Convert.IsDBNull(date))
            {
                return "";
            }
            else if ((date == null))
            {
                return "";
            }
            else if (date.ToString().Length < 3)
            {
                return "";
            }
            else
            {
                string[] arrDate = date.ToString().Split(new Char[] { '/' });
                return arrDate[1] + "/" + arrDate[0] + "/" + arrDate[2];
            }
        }

        public static string GetVietnameseDate(DateTime dDateTime)
        {
            switch (dDateTime.DayOfWeek)
            {
                case DayOfWeek.Sunday:
                    return "Chủ Nhật";

                case DayOfWeek.Monday:
                    return "Thứ Hai";

                case DayOfWeek.Tuesday:
                    return "Thứ ba";

                case DayOfWeek.Wednesday:
                    return "Thứ Tư";

                case DayOfWeek.Thursday:
                    return "Thứ Năm";

                case DayOfWeek.Friday:
                    return "Thứ Sáu";

                case DayOfWeek.Saturday:
                    return "Thứ Bảy";
            }
            return "";
        }

		public static object Replace_Quotes(string inString)
		{
			return inString.Replace(Convert.ToChar(39), Convert.ToChar(146));
		}

        public static DateTime ConvertDate2Data(object date)
        {
            if (Convert.IsDBNull(date))
            {
                return DateTime.Now;
            }
            else if (date == null)
            {
                return DateTime.Now;
            }
            else if (StringForNull(date).Equals(""))
            {
                return DateTime.Now;
            }
            else if (date.ToString().Length < 3)
            {
                return DateTime.Now;
            }
            else
            {
                string[] arrDate1 = date.ToString().Split(new Char[] { ' ' });
                string[] arrDate = arrDate1[0].Split(new Char[] { '/' });
                try
                {
                    return new DateTime(Int32.Parse(arrDate[2]), Int32.Parse(arrDate[0]), Int32.Parse(arrDate[1]));
                }catch(Exception ex){
                    return new DateTime(Int32.Parse(arrDate[2]), Int32.Parse(arrDate[1]), Int32.Parse(arrDate[0]));
                }
            }
        }

        public static string SubString(string str, int len)
        {
            string sTemp = "";
            if ((str != null) && (str.Length > 0))
            {
                if (str.Length <= len)
                {
                    return str;
                }
                else
                {
                    Int32 lenNext = str.IndexOf(' ', len);
                    if (lenNext == -1)
                    {
                        return str;
                    }
                    else
                    {
                        return str.Substring(0, str.IndexOf(' ', len)) + "...";
                    }
                }
            }
            else
            {
                return "";
            }
        }

        public static string SubStringWithChar(string str, int len)
        {
            string sTemp = "";
            if ((str != null) && (str.Length > 0))
            {
                if (str.Length <= len)
                {
                    return str;
                }
                else
                {
                    return str.Substring(0, len) + "...";
                }
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Ham tra ve chuoi con duoc cat voi so tu 'len'
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string SubStringWithWord(string str, int len)
        {
            string rStr = "";
            string[] sstr = str.Split(' ');

            if (str != null && sstr.Length > len)
            {
                for (int i = 0; i < len; i++)
                    rStr += sstr[i] + " ";
                rStr += "...";
                return rStr;
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// Xóa các tag HTML trong nội dung hiển thị
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string ConvertToHtml(string content)
        {
            // Regex objRegExpr = new Regex("<[^>]*?>");
            //string showString = objRegExpr.Replace(content
            //objRegExpr.Pattern = "<[^>]*?>"
            //Set showString = objRegExpr.Execute(fullString)
            //</?p>
            string pattern = @"<(.|\n)*?>";
            //string pattern = @"<(.)*?>";
            //string pattern = @"<.*?>";
            //string pattern = @"<(|/)p>";// remove tag <p>
            //<p>(.|\n)*?</p>"; 
            content = Regex.Replace(content, pattern, string.Empty);

            //content = System.Web.HttpUtility.HtmlEncode(content);
            //content = content.Replace("  ", "&nbsp;&nbsp;").Replace(
            //   "\t", "&nbsp;&nbsp;&nbsp;").Replace("\n", "<br>");
            return content;
        }

        public static string RemoveTagP(string content)
        {            
            string pattern = @"<(|/)p>";// remove tag <p>
            content = Regex.Replace(content, pattern, string.Empty);
            return content;
        }

        public static string PriceFormat(double price)
        {
            try
            {
                string[] str_tmp = price.ToString().Split(',');
                long price_tmp = Convert.ToInt64(str_tmp[0]);
                string str_price = "";
                long tmp;

                while (price_tmp >= 1000)
                {
                    tmp = price_tmp % 1000;
                    price_tmp = price_tmp / 1000;
                    if (tmp < 10)
                        str_price = ",00" + tmp.ToString() + str_price;
                    else if (tmp < 100)
                        str_price = ",0" + tmp.ToString() + str_price;
                    else
                        str_price = "," + tmp.ToString() + str_price;
                }
                str_price = price_tmp.ToString() + str_price;
                //if (Convert.ToInt32(str_tmp[1]) > 0)
                //    str_price += "," + str_tmp[1].ToString();
                return str_price;
            }
            catch
            {
                return price.ToString();
            }
        }

        public static string StringForDisplay(string str, int index)
        {
            if (String.IsNullOrEmpty(str))
                return String.Empty;
            if (str.Length <= index)
            {
                return str;
            }
            else
            {
                string str2 = str.Substring(index);
                int spaceFirst = str2.IndexOf(' ');
                if (spaceFirst != 0)
                {
                    return str.Substring(0, str.Substring(0, index).Length + spaceFirst);
                }
                else
                {
                    return str.Substring(0, index);
                }
            }
        }

        //public static string ConvertToHtml(string content)
        //{
        //    // Regex objRegExpr = new Regex("<[^>]*?>");
        //    //string showString = objRegExpr.Replace(content
        //    //objRegExpr.Pattern = "<[^>]*?>"
        //    //Set showString = objRegExpr.Execute(fullString)
        //    //</?p>
        //    string pattern = @"<(.|\n)*?>";
        //    content = Regex.Replace(content, pattern, string.Empty);

        //    //content = System.Web.HttpUtility.HtmlEncode(content);
        //    //content = content.Replace("  ", "&nbsp;&nbsp;").Replace(
        //    //   "\t", "&nbsp;&nbsp;&nbsp;").Replace("\n", "<br>");
        //    return content;
        //}
        
	}
}
